package src.controller;

import java.io.File;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;

public class PlayerKeyMap{
	private final String defaultKeyMap;
	private File keyMapFile;
 
	private HashMap<Integer, String> keyHashMap;
	
	public PlayerKeyMap(String keyMapPath){
		defaultKeyMap = "data" + File.separator + "controller" + File.separator + "default";

		keyHashMap = new HashMap<Integer, String>();

		loadDefaultKeys();
		
		if(keyMapPath == null)
			return;	
		
		keyMapFile = new File(keyMapPath);
	
		if(!keyMapFile.canRead()){
			return;
		}

		loadKeys(keyMapFile);
	}



	public String translateKey(int keyval){
		return keyHashMap.get(keyval);
	}

	public void saveKeyMap(){
		try{



		FileWriter fw = new FileWriter(keyMapFile);
		PrintWriter pw = new PrintWriter(fw);

		Set<Map.Entry<Integer, String>> setOfPairs = keyHashMap.entrySet();

		Iterator<Map.Entry<Integer, String>> pairsIt = setOfPairs.iterator();

		Map.Entry<Integer, String> curKeyPair;
		while(pairsIt.hasNext()){
			curKeyPair = pairsIt.next();

			pw.println(curKeyPair.getValue() + "\t\t" + curKeyPair.getKey());
		}

		pw.flush();


		
		} catch(IOException e){
			System.out.println("ERROR OUTPUTTING TO FILE " + keyMapFile.getName());
		}
	}		

	private void loadDefaultKeys(){

		File defaultKeysFile = new File(defaultKeyMap);
		
		if(!defaultKeysFile.canRead()){
			System.out.println("ERROR: UNABLE TO OPEN UP THE DEFAULT KEY MAP");
			return;
		}
		
		loadKeys(defaultKeysFile);
	
	}	

	private void loadKeys(File f){
		try{



		FileReader fr = new FileReader(f);
		BufferedReader br = new BufferedReader(fr);
		String curline = "";

		curline = br.readLine();


		while(curline != null){
			String[] curlinesplit = curline.split("\\s+");
		
			if(curlinesplit.length == 2){
				String command = curlinesplit[0];
				Integer keyval = new Integer(curlinesplit[1]);

				keyHashMap.put(keyval, command);
			}

			curline = br.readLine();
		}


	
		} catch(IOException e){
			System.out.println("ERROR READING FROM FILE " + f.getName());
		}
	}				

}
